﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Workflow.Common;
using Workflow.Dto;
using Workflow.IService;
using Workflow.Web.Common;
using Workflow.Web.Models;

namespace Workflow.Web.Controllers
{

    [HandleError]
    [Localization] 
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        public IUserManager UserManager { get; set; }
        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {

            ViewData["Title"] = Workflow.Resource.Global.LogOn;
			if (Request.Cookies[ConfigReader.WorkFlowCookieName] != null)
            {
                string name = Request.Cookies[ConfigReader.WorkFlowCookieName] [ConfigReader.NameCookie];
                string password = Request.Cookies[ConfigReader.WorkFlowCookieName][ConfigReader.PasswordCookie];
                string s = EncryptString.DecryptDES(name, ConfigReader.PrivateKey);
                string s1 = EncryptString.DecryptDES(password, ConfigReader.PrivateKey);
                if (name != null) ViewData["name"] = EncryptString.DecryptDES(name, ConfigReader.PrivateKey);
                if (password != null) ViewData["password"] = EncryptString.DecryptDES(password, ConfigReader.PrivateKey);
            }
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
        	long userId;
        	UserQueryDto userQueryDto = null;

			if(Int64.TryParse(model.UserName,out userId))
			{
				 userQueryDto = UserManager.UserLogin(userId, model.Password);
			}
		
            if (userQueryDto!=null)
            {
                Session[ConfigReader.AuthorizeSessionUserGroup] = userQueryDto.UserGroup;
                Session[ConfigReader.AuthorizeSessionUserName] = userQueryDto.UserName;
                Session[ConfigReader.AuthorizeSessionUserRole] = userQueryDto.UserRole; 
                Session[ConfigReader.AuthorizeSessionUserID] = userQueryDto.UserID;
                Session[ConfigReader.AuthorizeSessionUserGroupCode] = userQueryDto.UserGroupCode;
                Session[ConfigReader.AuthorizeSessionUserRoleCode] = userQueryDto.USerRoleCode;
                if(model.RememberMe)
                {
                    HttpCookie _cookie = new HttpCookie(ConfigReader.WorkFlowCookieName);
                    _cookie.Expires = DateTime.Now.AddYears(1);
                    _cookie.Values.Add(ConfigReader.NameCookie,EncryptString.EncryptDES(userQueryDto.UserID.ToString(),ConfigReader.PrivateKey));
                    _cookie.Values.Add(ConfigReader.PasswordCookie, EncryptString.EncryptDES(userQueryDto.PassWord, ConfigReader.PrivateKey));
                    HttpContext.Response.SetCookie(_cookie); 
                }
                else
                {
                    if (Request.Cookies[ConfigReader.WorkFlowCookieName] != null) 
                    {
                        HttpCookie _cookie = new HttpCookie(ConfigReader.WorkFlowCookieName);
                        _cookie.Expires = DateTime.Now.AddDays(-1d);
                        Response.Cookies.Add(_cookie); 
                    }   
                }
                return RedirectToAction("Index", "Home");
            }
            
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                return View(model);
            }
             //return View("");
            //if (ModelState.IsValid)
            //{
            //    if (MembershipService.ValidateUser(model.UserName, model.Password))
            //    {
            //        FormsService.SignIn(model.UserName, model.RememberMe);
            //        if (!String.IsNullOrEmpty(returnUrl))
            //        {
            //            return Redirect(returnUrl);
            //        }
            //        else
            //        {
            //            return RedirectToAction("Index", "Home");
            //        }
            //    }
            //    else
            //    {
            //        ModelState.AddModelError("", "The user name or password provided is incorrect.");
            //    }
            //}

            // If we got this far, something failed, redisplay form
          
        }
        private void SaveLoginCookie(LogOnModel model)
        {
            if (model.RememberMe)
            {
                
            }  
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
           // FormsService.SignOut();
            Session.Clear();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        
        }
        public ActionResult NoPrivilege()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
